// const BASE_URL = process.env.VUE_APP_API_BASE_URL
import {visitorToken} from "../common/global";

const BASE_URL = import.meta.env.VITE_BASE_API

//请求次数
let reqTimes = 0

type methodTypes = 'OPTIONS' | 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'TRACE' | 'CONNECT'

const req = (url: string, data: any, method: methodTypes, needToken: boolean, json: boolean): Promise<any> => {
    /*加载弹框*/
    uni.showLoading({
        title: '请稍候...',
        mask: true
    });
    return new Promise((resolve,reject)=>{
        reqTimes++
        uni.request({
            url:BASE_URL+url,
            data: needToken ? Object.assign({
                token: uni.getStorageSync('token') || visitorToken // 游客token兜底
            }, data) : data,
            header:{
                'Accept': 'application/json',
                'Content-Type': json ? 'application/json' : 'application/x-www-form-urlencoded',
            },
            method,
            success: async (res) => {
                if (res.statusCode === 200){
                    resolve(res.data)
                }else if (res.data?.error === 'invalid_token') {
                    uni.showToast({
                        title: '登录失效',
                        mask: true,
                        icon: 'none',
                        duration: 1500
                    });

                    await setTimeout(() => {
                        uni.reLaunch({
                            url: `/pages/index/index?reload=1`
                        })
                    }, 1500);
                } else {
                    reject(res)
                }
            },
            fail: (err) => {
                reject(err)
            },
            complete: () => {
                reqTimes--
                if(!reqTimes){
                    uni.hideLoading()
                }
            }
        })
    })
}

const request = {
    get: (url: string, data: any, needToken: boolean = false, json: boolean = false) => req(url, data, 'GET', needToken,json),
    post: (url: string, data: any,needToken: boolean = false, json: boolean = false)=> req(url, data, 'POST',needToken,json),
    put: (url: string, data: any,needToken: boolean = false, json: boolean = false)=> req(url, data, 'PUT',needToken,json),
    delete: (url: string, data: any,needToken: boolean = false, json: boolean = false) => req(url, data, 'DELETE',needToken,json)
}

export default request
export {request}
